package com.cqndt.disaster.device.parsing;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cqndt.disaster.device.common.util.GetRequestJsonUtils;
import com.cqndt.disaster.device.common.util.Result;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "gnss")
public class GnssAccess {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static Map<String, String> keys = new HashMap<>(16);


    @PostMapping(value = "auth")
    public Result auth(String account, String password) {
        Result result = new Result();
        String key = String.valueOf(Math.abs((account + password).hashCode()));
        keys.put("key", key);
        result.setMsg(key);
        return result;
    }

    @PostMapping(value = "upload")
    public Result upload(HttpServletRequest request) {
        String key = request.getHeader("key");
        if (null != key && keys.get("key") != null) {
            if (key.endsWith(keys.get("key"))) {

                String requestJsonString = null;
                try {
                    requestJsonString = GetRequestJsonUtils.getRequestJsonString(request);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                List<Map<String, Object>> mapList = (List<Map<String, Object>>) JSONArray.parse(requestJsonString);
                for (Map<String, Object> stringObjectMap : mapList) {
                    stringObjectMap.put("type", "4");
                }

                String s = JSON.toJSONString(mapList);
                rabbitTemplate.convertAndSend("test2", s);
                return new Result().success("推送成功");
            }
        }
        return new Result().failure(1, "错误的鉴权");
    }

}
